package com.hsurosy.hsuchain.nft.sms;

import com.google.common.collect.Maps;
import com.hsurosy.hsuchain.nft.base.utils.RestClientUtils;
import com.hsurosy.hsuchain.nft.lock.DistributeLock;
import com.hsurosy.hsuchain.nft.sms.response.SmsSendResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import java.util.Map;

import static com.hsurosy.hsuchain.nft.base.response.ResponseCode.SYSTEM_ERROR;


/**
 * 实际的短信服务实现
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-05 5:09
 * @Description
 * @Version: v1.0.0
 */
@Slf4j
@Data
public class SmsServiceImpl implements SmsService {

    /**
     * 日志记录器，用于记录日志信息。
     */
    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    /**
     * 短信服务API的host地址
     */
    private String host;

    /**
     * 短信服务API的路径
     */
    private String path;

    /**
     * API的授权appcode
     */
    private String appcode;

    /**
     * 短信签名ID
     */
    private String smsSignId;

    /**
     * 短信模板ID
     */
    private String templateId;

    /**
     * 发送短信验证码
     * <p>
     * 使用分布式锁确保同一手机号在并发环境下不会多次发送短信。
     *
     * @param phoneNumber 接收验证码的手机号码
     * @param code        验证码
     * @return SmsSendResponse 发送短信的响应结果
     */
    @DistributeLock(scene = "SEND_SMS", keyExpression = "#phoneNumber")
    @Override
    public SmsSendResponse sendMsg(String phoneNumber, String code) {
        SmsSendResponse smsSendResponse = new SmsSendResponse();

        String method = "POST";

        // 构建请求头，加入授权信息
        Map<String, String> headers = Maps.newHashMapWithExpectedSize(1);
        headers.put("Authorization", "APPCODE " + appcode);

        // 构建请求参数，包括手机号、验证码和模板信息
        Map<String, String> querys = Maps.newHashMapWithExpectedSize(4);
        querys.put("mobile", phoneNumber);
        querys.put("param", "**code**:" + code + ",**minute**:5");
        querys.put("smsSignId", smsSignId);
        querys.put("templateId", templateId);

        // 构建请求体
        Map<String, String> bodys = Maps.newHashMapWithExpectedSize(2);

        try {
            // 发送POST请求到短信服务
            ResponseEntity response = RestClientUtils.doPost(host, path, headers, querys, bodys);
            // 如果响应状态码为2xx，则表示短信发送成功
            if (response.getStatusCode().is2xxSuccessful()) {
                smsSendResponse.setSuccess(true);
            }
        } catch (Exception e) {
            // 记录异常日志并设置响应失败信息
            logger.error("sendMsg error", e);
            smsSendResponse.setSuccess(false);
            smsSendResponse.setResponseCode(SYSTEM_ERROR.name());
            smsSendResponse.setResponseMessage(StringUtils.substring(e.toString(), 0, 1000));
        }

        // 返回短信发送结果
        return smsSendResponse;
    }
}
